<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-row :gutter="20">
        <a-col :sm="24" :md="16" :xl="16">
          <a-form-model
            layout="inline"
            ref="myForm"
            :rules="validatorRules"
            :model="form"
            :label-col="{ style: { width: '150px' } }"
          >
            <a-row :gutter="24">
              <a-col :sm="24" :md="24" :xl="24">
                <a-form-model-item label="网点区域">
                  <a-row :gutter="5">
                    <a-col :span="6">
                      <a-select
                        placeholder="请选择省"
                        v-model="form.provinceCode"
                        @change="(e, data) => addressChange(e, 'cityOptions', 'province', data.key)"
                      >
                        <a-select-option v-for="item in provinceOptions" :key="item.name" :value="item.code">
                          {{ item.name }}
                        </a-select-option>
                      </a-select>
                    </a-col>
                    <a-col :span="6">
                      <a-select
                        placeholder="请选择市"
                        v-model="form.cityCode"
                        @change="(e, data) => addressChange(e, 'areaOptions', 'city', data.key)"
                      >
                        <a-select-option v-for="item in cityOptions" :key="item.name" :value="item.code">
                          {{ item.name }}
                        </a-select-option>
                      </a-select>
                    </a-col>
                    <a-col :span="6">
                      <a-select
                        placeholder="请选择区"
                        v-model="form.areaCode"
                        @change="(e, data) => addressChange(e, 'streetOptions', 'area', data.key)"
                      >
                        <a-select-option v-for="item in areaOptions" :key="item.name" :value="item.code">
                          {{ item.name }}
                        </a-select-option>
                      </a-select>
                    </a-col>
                    <a-col :span="6">
                      <a-select
                        placeholder="请选择街道"
                        v-model="form.streetCode"
                        @change="(e, data) => addressChange(e, '', 'street', data.key)"
                      >
                        <a-select-option v-for="item in streetOptions" :key="item.name" :value="item.code">
                          {{ item.name }}
                        </a-select-option>
                      </a-select>
                    </a-col>
                  </a-row>
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="网点名称" prop="networkId">
                  <a-select placeholder="请选择网点" v-model="form.networkId" @change="updateNetwork">
                    <a-select-option v-for="item in networkOptions" :key="item.code" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="商家">
                  <a-select disabled v-model="form.businessId">
                    <a-select-option v-for="item in agentOptions" :key="item.code" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="设备ID">
                  <a-input disabled v-model="form.deviceId"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="主板ID" prop="mainboardId">
                  <a-input
                    allowClear
                    class="per100"
                    :disabled="role === 'business'"
                    placeholder="请输入"
                    v-model="form.mainboardId"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="地点" prop="subject">
                  <a-input allowClear placeholder="请输入" v-model="form.subject" />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="设备别名" prop="deviceName">
                  <a-input allowClear placeholder="请输入" v-model="form.deviceName" />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="设备类型" prop="deviceType">
                  <j-dict-select-tag
                    v-model="form.deviceType"
                    @input="
                      () => {
                        $refs.myForm.validateField('deviceType')
                      }
                    "
                    placeholder="请选择"
                    dictCode="deviceType"
                    :disabled="role === 'business'"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="格子类型" prop="cellType">
                  <j-dict-select-tag
                    v-model="form.cellType"
                    @input="
                      () => {
                        $refs.myForm.validateField('cellType')
                      }
                    "
                    placeholder="请选择"
                    dictCode="cellType"
                    :disabled="role === 'business'"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="格子数量">
                  <a-input-number class="per100" disabled v-model="form.cellNum" />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="SIM卡信息">
                  <a-input allowClear placeholder="请输入" :disabled="role === 'business'" v-model="form.simMsg" />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="物联网卡卡号">
                  <a-input
                    allowClear
                    class="per100"
                    placeholder="请输入"
                    :disabled="role === 'business'"
                    v-model="form.networkCardNum"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="设备出售时间">
                  <a-date-picker
                    class="per100"
                    v-model="form.equipmentSalesTime"
                    :disabled="role === 'business'"
                    valueFormat="YYYY-MM-DD"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="物联网卡激活日期" prop="networkCardActiveTime">
                  <a-date-picker
                    class="per100"
                    :disabled="role === 'business'"
                    v-model="form.networkCardActiveTime"
                    valueFormat="YYYY-MM-DD"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="保修周期（月）">
                  <a-input-number
                    class="per100"
                    placeholder="请输入"
                    :disabled="role === 'business'"
                    v-model="form.warrantyPeriod"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="计费方式" prop="billingMethod">
                  <j-dict-select-tag
                    @input="
                      () => {
                        $refs.myForm.validateField('billingMethod')
                      }
                    "
                    v-model="form.billingMethod"
                    placeholder="请选择"
                    dictCode="billingMethod"
                    :disabled="role === 'business'"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="是否存手机" prop="saveMobile">
                  <j-dict-select-tag
                    v-model="form.saveMobile"
                    @input="
                      () => {
                        $refs.myForm.validateField('saveMobile')
                      }
                    "
                    placeholder="请选择"
                    dictCode="userYn"
                    :disabled="role === 'business'"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12" v-if="role !== 'business'">
                <a-form-model-item label="是否支持中途取包" prop="midwayPick">
                  <j-dict-select-tag
                    v-model="form.midwayPick"
                    @input="
                      () => {
                        $refs.myForm.validateField('midwayPick')
                      }
                    "
                    placeholder="请选择"
                    dictCode="midwayPick"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12" v-if="form.midwayPick === '0' && role !== 'business'">
                <a-form-model-item label="中途取包次数" prop="midwayPickTimes">
                  <a-input-number class="per100" placeholder="请输入" v-model="form.midwayPickTimes" />
                </a-form-model-item>
              </a-col>

              <!-- 新增 -->
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="是否带广告屏">
                  <j-dict-select-tag
                    allowClear
                    v-model="form.advertisingScreen"
                    placeholder="请选择"
                    dictCode="userYn"
                    :disabled="role === 'business'"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="显示亮度（0-15）">
                  <a-input-number
                    class="per100"
                    placeholder="请输入"
                    :min="0"
                    :max="15"
                    v-model="form.displayBrightness"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="音量（0-5）">
                  <a-input-number class="per100" placeholder="请输入" :min="0" :max="5" v-model="form.volume" />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="设备状态" prop="equipmentStatus">
                  <j-dict-select-tag
                    @input="
                      () => {
                        $refs.myForm.validateField('equipmentStatus')
                      }
                    "
                    v-model="form.equipmentStatus"
                    placeholder="请选择"
                    dictCode="equipmentStatus"
                  />
                </a-form-model-item>
              </a-col>

              <a-col :sm="24" :md="24" :xl="12" v-if="!this.hasRole('business')">
                <a-form-model-item label="是否隐藏">
                  <j-dict-select-tag allowClear v-model="form.hideStatus" placeholder="请选择" dictCode="hidden" />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12" v-if="showHiddenOption">
                <a-form-model-item label="逻辑时间(分钟)">
                  <a-input allowClear v-model="form.logicTime" placeholder="时间" />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12" v-if="showHiddenOption">
                <a-form-model-item label="逻辑单数(单)">
                  <a-input allowClear v-model="form.logicOrderNum" placeholder="单数" />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="是否定时清箱">
                  <j-dict-select-tag v-model="form.clearContainer" placeholder="请选择" dictCode="clearContainer" />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12" v-if="parseInt(form.clearContainer) === 1">
                <a-form-model-item label="定时清箱周期">
                  <a-input placeholder="请输入天数" class="per100" v-model="form.taskCycle" addon-after="天" />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12" v-if="parseInt(form.clearContainer) === 1">
                <a-form-model-item label="任务时间">
                  <a-time-picker class="per100" v-model="form.taskTime" format="HH:mm" valueFormat="HH:mm" />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="最新清箱时间">
                  <a-input disabled class="per100" v-model="form.latestCleaningTime" />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="24">
                <a-form-model-item label=" " :colon="false">
                  <a-button type="primary" :loading="loading" @click="onSubmit">提交</a-button>
                  <a-button class="ml10" @click="closeCurrent()">返回</a-button>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-col>
        <a-col :sm="24" :md="8" :xl="8" class="t-c">
          <a-avatar
            shape="square"
            :src="form.qrCode"
            :style="{ width: '100%', height: '100%' }"
            alt="未生成或未找到二维码"
            >未生成或未找到二维码</a-avatar
          >
          <div class="btn-box mt10">
            <a-button icon="qrcode" @click="generateQrCode" type="primary">
              生成
            </a-button>
            <a-button icon="download" @click="download" class="ml10">下载</a-button>
          </div>
        </a-col>
      </a-row>
    </div>
  </a-card>
</template>

<script>
import store from '@/store/'
import Api from '@/api/DeviceManage/DeviceList'
import CommonApi from '@/api/Common/index'
import { httpAction, getAction, getFileFromBase64 } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'

export default {
  name: 'DeviceUpdate',
  inject: ['closeCurrent'],
  data() {
    return {
      form: {
        id: 0,
        provinceCode: undefined, // 省
        cityCode: undefined, // 市
        areaCode: undefined, // 区
        streetCode: undefined, // 镇
        networkId: undefined, // 网点
        businessId: undefined, // 商家id
        mainboardId: '', // 主板id
        deviceName: '', // 设备别名
        deviceType: undefined, // 设备类型
        cellType: undefined, // 格子类型
        cellNum: undefined, // 格子数量
        simMsg: '', // SIM卡信息
        networkCardNum: '', // 物联网卡卡号
        equipmentSalesTime: '', // 设备出售时间
        networkCardActiveTime: '', // 物联网卡激活日期
        warrantyPeriod: undefined, // 保修周期(月)
        billingMethod: undefined, // 计费方式
        saveMobile: undefined, // 是否存手机
        midwayPick: undefined, // 是否支持中途取包
        advertisingScreen: undefined, // 是否带广告屏
        displayBrightness: undefined, // 显示亮度
        volume: undefined, // 音量
        equipmentStatus: undefined, // 设备状态
        hideStatus: undefined, // 是否隐藏
        clearContainer: undefined, // 是否定时清箱
        latestCleaningTime: undefined, // 最新清箱时间
        taskCycle: undefined,
        taskTime: undefined, // 任务时间
        versionId: undefined // 客户端版本号
      },
      loading: false,
      provinceOptions: [],
      cityOptions: [],
      areaOptions: [],
      streetOptions: [],
      networkOptions: [],
      agentOptions: [],
      validatorRules: {
        networkId: [{ required: true, message: '网点不能为空', trigger: 'change' }],
        mainboardId: [
          { required: true, message: '主板ID不能为空', trigger: 'change' },
          {
            validator: (rule, value, callback) =>
              validateDuplicateValue('t_machine', 'mainboard_id', value, this.form.id, callback),
            trigger: 'blur'
          }
        ],
        deviceType: [{ required: true, message: '设备类型不能为空', trigger: 'change' }],
        deviceName: [{ required: true, message: '设备别名不能为空', trigger: 'change' }],
        cellType: [{ required: true, message: '格子类型不能为空', trigger: 'change' }],
        networkCardActiveTime: [{ required: true, message: '物联网卡激活日期不能为空', trigger: 'change' }],
        billingMethod: [{ required: true, message: '计费方式不能为空', trigger: 'change' }],
        saveMobile: [{ required: true, message: '是否存手机不能为空', trigger: 'change' }],
        midwayPick: [{ required: true, message: '是否支持中途取包不能为空', trigger: 'change' }],
        equipmentStatus: [{ required: true, message: '设备状态不能为空', trigger: 'change' }],
        midwayPickTimes: [{ required: true, message: '中途取包次数不能为空', trigger: 'change' }]
      },
      role: 'agent_maintain' // admin(admin,developer),business(business, agent),agent_maintain
    }
  },
  computed: {
    showHiddenOption() {
      return Number(this.form.hideStatus || '') === 0 && !this.hasRole('business')
    }
  },
  created() {
    if (this.hasRole('admin') || this.hasRole('developer')) {
      this.role = 'admin'
    } else if (this.hasRole('business') || this.hasRole('agent')) {
      this.role = 'business'
    }
    this.getDetails()
    this.getAddress('provinceOptions')
  },
  methods: {
    // 获取详情
    getDetails() {
      getAction(Api.queryId, { id: this.$route.params.id })
        .then(async res => {
          if (res.code === 200) {
            this.form = res.result
            if (this.form.provinceCode) {
              await this.addressChange(this.form.provinceCode, 'cityOptions', 'province')
              this.agentList('agentOptions', { provinceCode: this.form.provinceCode })
            }
            if (this.form.cityCode) {
              await this.addressChange(this.form.cityCode, 'areaOptions', 'city')
              this.agentList('agentOptions', { cityCode: this.form.cityCode })
            }
            if (this.form.areaCode) {
              await this.addressChange(this.form.areaCode, 'streetOptions', 'area')
              this.agentList('agentOptions', { areaCode: this.form.areaCode })
            }
            if (this.form.streetCode) {
              await this.addressChange(this.form.streetCode, '', 'street')
              this.agentList('agentOptions', { streetCode: this.form.streetCode })
            }
          } else {
            this.$message.error(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 获取地址
    getAddress(name, data) {
      getAction(CommonApi.addressList, data).then(res => {
        this[name] = res.result
      })
    },
    // 地址改变
    addressChange(e, name, key, cn) {
      let obj = {}
      // 改变重置后面市区镇商家网点设备
      if (key === 'province') {
        obj = {
          cityCode: undefined,
          areaCode: undefined,
          streetCode: undefined,
          businessId: undefined,
          networkId: undefined,
          deviceId: undefined
        }
        this.cityOptions = []
        this.areaOptions = []
        this.streetOptions = []
      } else if (key === 'city') {
        obj = {
          areaCode: undefined,
          streetCode: undefined,
          businessId: undefined,
          networkId: undefined,
          deviceId: undefined
        }
        this.areaOptions = []
        this.streetOptions = []
      } else if (key === 'area') {
        obj = {
          streetCode: undefined,
          networkId: undefined,
          businessId: undefined,
          deviceId: undefined
        }
        this.streetOptions = []
      } else if (key === 'street') {
        obj = {
          businessId: undefined,
          networkId: undefined,
          deviceId: undefined
        }
      } else if (key === 'agentCode') {
        obj = {
          businessId: undefined,
          networkId: undefined,
          deviceId: undefined
        }
      }

      this.agentOptions = []
      this.networkOptions = []
      this.deviceOptions = []
      if (cn) {
        this.form = { ...this.form, ...obj }
      }
      if (name && e) {
        this.getAddress(name, { [`${key}Code`]: e })
        this.form[`${key}Cn`] = cn
      }
      // 区和镇改变重新请求商家
      if (key === 'province' || key === 'city' || key === 'area' || key === 'street') {
        if (e) {
          // this.agentList('agentOptions', { [`${key}Code`]: e })
          this.agentList('networkOptions', { [`${key}Code`]: e, type: 1 })
        }
      }
    },

    // 获取商家网点设备下拉列表
    agentList(name, data) {
      getAction(CommonApi.agentList, data).then(res => {
        this[name] = res.result
      })
    },

    download() {
      getFileFromBase64(this.form.qrCode)
    },

    generateQrCode() {
      if (!this.form.id) {
        return
      }
      getAction(Api.qrCode + this.form.id).then(res => {
        this.$set(this.form, 'qrCode', res.message)
      })
    },

    updateNetwork(code) {
      getAction(CommonApi.agentList, { networkCode: code, usage: 'business' }).then(res => {
        if (res.result && res.result.length > 0) {
          this.form.businessId = res.result[0].code
          this.agentOptions = res.result
        }
      })
    },

    // 提交
    onSubmit() {
      this.$refs.myForm.validate(valid => {
        if (valid) {
          let url = Api.edit
          let method = 'put'
          this.loading = true
          if (Number(this.form.hideStatus) === 1) {
            this.form.logicTime = 0
            this.form.logicOrderNum = 0
          }
          if (Number(this.form.midwayPick) === 1) {
            this.form.midwayPickTimes = 0
          }
          httpAction(url, this.form, method)
            .then(res => {
              if (res.code === 200) {
                this.$message.success(res.message)
                this.closeCurrent()
                this.$router.push('/deviceManage/deviceList')
              } else {
                this.$message.error(res.message)
              }
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },

    hasRole(name) {
      const hasRole = store.getters.roles.find(item => {
        return item.roleCode === name
      })
      return !!hasRole
    }
  }
}
</script>

<style scoped></style>

